package thread.thread_04_21.thread_safe.Phenomenon;

/**
 * @author bruin_du
 * @description 使用synchronized
 * @date 2022/5/2 23:02
 **/
public class UseSynchronized {
    // 定义一个共享的数据
    static int r = 0;

    // 定义加减的次数
    static final int COUNT = 1000000;

    //定义一个公共的静态对象
    static Object object = new Object();

    static class Add extends Thread {
        @Override
        public void run() {
            //对该对象进行加锁
            synchronized (object) {
                for (int i = 0; i < COUNT; i++) {
                    r++;
                }
            }
        }
    }

    static class Sub extends Thread {
        @Override
        public void run() {
            //同一把锁,有互斥性
            synchronized (object) {
                for (int i = 0; i < COUNT; i++) {
                    r--;
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Add add = new Add();
        add.start();

        Sub sub = new Sub();
        sub.start();

        add.join();
        sub.join();

        //结果始终为预期结果0
        System.out.println(r);
    }
}
